package fastwave.cloud.demo.fastwave.biz.publisher.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import fastwave.cloud.demo.fastwave.biz.publisher.domain.MsgLog;
import fastwave.cloud.demo.fastwave.biz.publisher.service.MsgLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: MQMessgeJob</p>
 *
 * @author: dwLiu
 * @date: 2020/4/9 15:31
 */
//@Component
//@EnableScheduling
public class MQMessgeJob {

    private static Logger logger = LoggerFactory.getLogger(MQMessgeJob.class);

    @Autowired
    private MsgLogService msgLogService;

    @Resource(name = "TemplateReliable")
    RabbitTemplate rabbitTemplate;

    /**
     * 定时扫描记录表，将发送状态为-1且未超重发次数的消息再次发送，超过重发次数，必要时人工干预，生产环境中可以单独部署定时任务
     */
    @Scheduled(cron = "10/10 * * * * ?")
    public void scanNoConfirmMsg(){
        QueryWrapper<MsgLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MsgLog::getStatus, -1)
                .eq(MsgLog::getTryCount, 3);
        try {
            List<MsgLog> msgLogList = msgLogService.list(queryWrapper);
            for (MsgLog msgLog:msgLogList){
                msgLog.setTryCount(msgLog.getTryCount()+1);
                msgLogService.updateById(msgLog);

                Message message = MessageBuilder.withBody(msgLog.getMsg().getBytes()).setMessageId(msgLog.getMsgId()).build();
                rabbitTemplate.convertAndSend(msgLog.getExchange(),msgLog.getRoutingKey(),message,new CorrelationData(msgLog.getMsgId()));
            }
        } catch (Exception e) {
            logger.error("扫描业务出错，信息："+e.getMessage());
        }
    }

}
